package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"servers/basic/inits"
	"servers/untils"

	"servers/pkg"
	"strconv"

	__ "servers/basic/proto"
	"servers/handler/models"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedCleanServer
}

// SayHello implements helloworld.GreeterServer
// 短信发送
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	aLiYun := untils.AliSms{}
	intn := rand.Intn(9000) + 1000
	count, _ := inits.RedisDB.Get(inits.Ctx, "sendSmsCount:"+in.Mobile).Int()
	if count == 5 {
		return nil, fmt.Errorf("短信验证码一分钟内只能发送五次")
	}
	err := aLiYun.AliYun(in.Mobile, strconv.Itoa(intn))
	if err != nil {
		return nil, err
	}
	inits.RedisDB.Set(inits.Ctx, "SendSms:"+in.Mobile, intn, time.Minute*15)
	inits.RedisDB.Incr(inits.Ctx, "sendSmsCount:"+in.Mobile)
	inits.RedisDB.Expire(inits.Ctx, "sendSmsCount:"+in.Mobile, time.Minute*1)

	return &__.SendSmsResp{}, nil
}

// 用户注册
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	user := models.User{
		Username: in.Username,
		Password: pkg.Md5(in.Password) + "123",
		Mobile:   in.Mobile,
		Nickname: in.Nickname,
		HendImg:  in.HendImg,
		Sex:      in.Sex,
	}
	if err := user.GetUserByMobile(); err != nil {
		return nil, err
	}
	if user.Id > 0 {
		return nil, errors.New("该手机号已存在，禁止重复注册")
	}
	get := inits.RedisDB.Get(inits.Ctx, "SendSms:"+in.Mobile).Val()
	if get != in.SmsCode {
		return nil, errors.New("短信验证码错误，请重新输入")
	}
	if err := user.CreateUser(); err != nil {
		return nil, errors.New("用户注册失败")
	}
	return &__.RegisterResp{
		Id: int64(user.Id),
	}, nil
}

// 登录
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	user := models.User{
		Username: in.Username,
		Password: in.Password,
		Mobile:   in.Mobile,
	}
	if err := user.GetUserByMobile(); err != nil {
		return nil, err
	}
	if user.Id == 0 {
		return nil, errors.New("该用户不存在，请前往注册")
	}
	if user.Password != pkg.Md5(in.Password)+"123" {
		return nil, errors.New("输入的密码有误，请重新输入")
	}
	get := inits.RedisDB.Get(inits.Ctx, "SendSms:"+in.Mobile).Val()
	if get != in.SmsCode {
		return nil, errors.New("短信验证码错误，请重新输入")
	}

	return &__.LoginResp{
		Id: int64(user.Id),
	}, nil
}

// 服务预约
func (s *Server) CreateProject(_ context.Context, in *__.CreateProjectReq) (*__.CreateProjectResp, error) {
	project := models.Project{
		Address:          in.Address,
		CleanType:        uint(in.CleanType),
		CleanPrice:       uint(float64(in.BeginPrice*in.CleanArea) * 0.5),
		CleanTime:        uint(in.CleanTime),
		CleanDesc:        in.CleanDesc,
		CleanArea:        uint(in.CleanArea),
		CleanCoefficient: uuid.NewString(),
		Status:           uint(in.Status),
		BeginPrice:       40,
	}
	if err := project.CreateProject(); err != nil {
		return nil, errors.New("订单创建失败")
	}
	return &__.CreateProjectResp{
		Id: int64(project.Id),
	}, nil
}

// 服务列表展示
func (s *Server) GetProjectList(_ context.Context, in *__.GetProjectListReq) (*__.GetProjectListResp, error) {
	var prosList []*__.ProjectList
	//get := inits.RedisDB.Get(inits.Ctx, "ProjectList").Val()

	var pro models.Project
	list, err := pro.GetProjectList()
	if err != nil {
		return nil, errors.New("服务列表展示失败")
	}
	for _, project := range list {
		prosList = append(prosList, &__.ProjectList{
			Id:               int64(project.Id),
			Address:          project.Address,
			CleanType:        int64(project.CleanType),
			CleanPrice:       int64(project.CleanPrice),
			CleanTime:        int64(project.CleanTime),
			CleanDesc:        project.CleanDesc,
			CleanArea:        int64(project.CleanArea),
			CleanCoefficient: project.CleanCoefficient,
			Status:           int64(project.Status),
			BeginPrice:       int64(project.BeginPrice),
		})
	}

	return &__.GetProjectListResp{
		List: prosList,
	}, nil
}

// 创建订单
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	order := models.Order{
		OrderSn:     uuid.NewString(),
		UserId:      uint(in.UserId),
		CleanerId:   uint(in.CleanerId),
		Address:     in.Address,
		ServiceType: uint(in.ServiceType),
		OrderPrice:  uint(in.OrderPrice),
		OrderStatus: 1,
	}
	if err := order.CreateOrder(); err != nil {
		return nil, errors.New("订单创建失败")
	}
	return &__.CreateOrderResp{
		Id: int64(order.Id),
	}, nil
}

// 订单详情
func (s *Server) GetOrderDetail(_ context.Context, in *__.GetOrderDetailReq) (*__.GetOrderDetailResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	if err := order.GetOrderDetail(); err != nil {
		return nil, errors.New("订单详情获取失败")
	}
	return &__.GetOrderDetailResp{
		Id:          int64(order.Id),
		OrderSn:     order.OrderSn,
		UserId:      int64(order.UserId),
		CleanerId:   int64(order.CleanerId),
		ServiceType: int64(order.ServiceType),
		OrderPrice:  int64(order.OrderPrice),
		OrderStatus: int64(order.OrderStatus),
		Address:     order.Address,
	}, nil
}

// 修改订单状态
func (s *Server) UpdateOrder(_ context.Context, in *__.UpdateOrderReq) (*__.UpdateOrderResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	order.OrderStatus = uint(in.OrderStatus)
	if err := order.UpdateOrderStatus(); err != nil {
		return nil, errors.New("订单状态修改失败")
	}
	return &__.UpdateOrderResp{
		Id: int64(order.Id),
	}, nil
}

// 保洁师拒单
func (s *Server) DeleteOrder(_ context.Context, in *__.DeleteOrderReq) (*__.DeleteOrderResp, error) {
	var order models.Order
	order.Id = uint(in.Id)

	if err := order.DeleteOrder(); err != nil {
		return nil, errors.New("取消订单失败")
	}
	return &__.DeleteOrderResp{}, nil
}

// 获取用户手机号后四位
/*func (s *Server) GetUserMobileLastFour(_ context.Context, in *__.GetUserMobileLastFourReq) (*__.GetUserMobileLastFourResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	if err := order.GetOrderById(); err != nil {
		return nil, errors.New("该订单不存在")
	}
	var user models.User
	user.Mobile = in.Mobile
	if err := user.GetUserById(); err != nil {
		return nil, errors.New("获取用户信息失败")
	}
	if user.Mobile[7:11] != in.Mobile {
		return nil, errors.New("客户手机号后四位有误，请核对后输入")
	}

	return &__.GetUserMobileLastFourResp{
		Mobile:  user.Mobile,
		Message: "客户手机号核实成功",
	}, nil
}*/

// 切换接单模式
func (s *Server) UpdateOrderType(_ context.Context, in *__.UpdateOrderTypeReq) (*__.UpdateOrderTypeResp, error) {
	var cleaner models.Cleaner
	cleaner.Id = uint(in.CleanerId)
	cleaner.OrderType = uint(in.OrderType)
	if err := cleaner.UpdateOrderType(); err != nil {
		return nil, errors.New("订单模式切换失败")
	}
	return &__.UpdateOrderTypeResp{
		Id: int64(cleaner.Id),
	}, nil
}

// 客户支付
func (s *Server) UserPay(_ context.Context, in *__.UserPayReq) (*__.UserPayResp, error) {
	var order models.Order
	order.Id = uint(in.OrderId)
	order.UserId = uint(in.UserId)
	if err := order.GetOrderById(); err != nil {
		return nil, err
	}
	if order.Id == 0 {
		return nil, errors.New("该订单不存在")
	}
	if order.UserId != uint(in.UserId) {
		return nil, errors.New("该订单不是您的，无法支付")
	}
	if order.OrderStatus == 7 {
		return nil, errors.New("该订单已支付，无法继续支付")
	}
	aliPay := untils.Ali{}
	money := fmt.Sprintf("%.2d", order.OrderPrice)

	return &__.UserPayResp{
		PayUrl: aliPay.Alipay(order.OrderSn, money),
	}, nil
}
